from django.shortcuts import render

# Create your views here.
from rest_framework.generics import ListAPIView, RetrieveAPIView, UpdateAPIView, CreateAPIView
from question.serializers import *
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_201_CREATED
from django.http import JsonResponse
from rest_framework.viewsets import ModelViewSet
from django_redis import get_redis_connection


# 所有标签列表
class LabelListView(ListAPIView):
    serializer_class = LabelSerializer
    queryset = Label.objects.all()


# 用户关注的标签
class UserLabelListView(ListAPIView):
    serializer_class = LabelSerializer
    queryset = User.objects.all()

    def get_queryset(self):
        return self.request.user.labels.all()


# 最新回答的问题
class NewQuestionListView(ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

    def get_queryset(self):
        label_id = self.kwargs.get('id')
        if label_id != '-1':
            labels = Label.objects.get(pk=label_id)
            questions = labels.questions.all()
            return questions.filter(reply__gt=0).order_by('replytime')
        return self.queryset.filter(reply__gt=0).order_by('replytime')


# 热门回答的问题
class HotQuestionListView(ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

    def get_queryset(self):
        label_id = self.kwargs.get('id')
        if label_id != '-1':
            labels = Label.objects.get(pk=label_id)
            questions = labels.questions.all()
            return questions.filter(reply__gt=0).order_by('reply')
        return self.queryset.filter(reply__gt=0).order_by('reply')


# 等待回答的问题
class WaitQuestionListView(ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

    def get_queryset(self):
        label_id = self.kwargs.get('id')
        if label_id != '-1':
            labels = Label.objects.get(pk=label_id)
            question = labels.questions.all()
            return question.filter(reply__exact=0).order_by('createtime')
        return self.queryset.filter(reply__exact=0).order_by('createtime')


# 发布问题
class ReleaseQuestionAPIView(APIView):
    def post(self, request):
        data = request.data
        user = self.request.user
        data['user_id'] = user.id
        serializer = QuestionSimpleSerializer(data=data)
        if not serializer.is_valid():
            return Response(data=serializer.errors, status=HTTP_400_BAD_REQUEST)
        serializer.save()
        serializer.data['message'] = '发布ok'
        serializer.data['success '] = True

        # 返回值待修改S
        return Response(data=serializer.data, status=HTTP_201_CREATED)


# 问题详情
class QuestionInfoListView(RetrieveAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionInfoSerializer

    def get_queryset(self):
        question_id = self.kwargs.get('pk')
        return self.queryset.filter(pk=question_id)


# 问题有用(暂时用)

class UsefulQuestioView(View):
    def put(self, request, pk):
        user = request.user
        # (1)获取redis连接
        conn = get_redis_connection('hasthumbup')
        # (2)使用conn连接对象把text写入
        if conn.get('question_%s_%s' % (pk, user.id)):
            return JsonResponse({'message': '请勿重复操作', 'success': False})
        conn.setex('question_%s_%s' % (pk, user.id), 3600, 'useful')
        try:
            question = Question.objects.get(pk=pk)
        except Exception as e:
            return JsonResponse({'message': '请勿重复操作', 'success': False})
        question.useful_count += 1
        question.save()
        return JsonResponse({'message': 'ok', 'success': True})


# 问题无用(暂时用)

class UnUsefulQuestioView(View):
    def put(self, request, pk):
        user = request.user
        # (1)获取redis连接
        conn = get_redis_connection('hasthumbup')
        # (2)使用conn连接对象把text写入
        if conn.get('unquestion_%s_%s' % (pk, user.id)):
            return JsonResponse({'message': '请勿重复操作', 'success': False})
        conn.setex('unquestion_%s_%s' % (pk, user.id), 3600, 'unuseful')
        try:
            question = Question.objects.get(pk=pk)
        except Exception as e:
            return JsonResponse({'message': '请勿重复操作', 'success': False})
        question.unuseful_count += 1
        question.save()
        return JsonResponse({'message': 'ok', 'success': True})


"""以下博博"""


# 回答问题
class ReplyView(APIView):
    def post(self, request):
        data = request.data
        user = self.request.user
        data['user_id'] = user.id
        serializer = ReplySimpleSerializer0(data=data)
        if not serializer.is_valid():
            return Response(data=serializer.errors, status=HTTP_400_BAD_REQUEST)
        serializer.save()
        serializer.data['message'] = '发布ok'
        serializer.data['success '] = True

        # 返回值待修改S
        return Response(data=serializer.data, status=HTTP_201_CREATED)


# 回答有用
class AnswerUseful(View):
    def put(self, request, pk):
        user = request.user
        # (1)获取redis连接
        conn = get_redis_connection('hasthumbup')
        # (2)使用conn连接对象把text写入
        if conn.get('answer_%s_%s' % (pk, user.id)):
            return JsonResponse({'message': '请勿重复操作', 'success': False})
        conn.setex('answer_%s_%s' % (pk, user.id), 3600, 'useful')
        try:
            reply = Reply.objects.get(pk=pk)
        except Exception as e:
            return JsonResponse({'message': '请勿重复操作', 'success': False})
        reply.unuseful_count += 1
        reply.save()
        return JsonResponse({'message': 'ok', 'success': True})


# 回答无用


class AnswerUnuseful(View):
    def put(self, request, pk):
        user = request.user
        # (1)获取redis连接
        conn = get_redis_connection('hasthumbup')
        # (2)使用conn连接对象把text写入
        if conn.get('unanswer_%s_%s' % (pk, user.id)):
            return JsonResponse({'message': '请勿重复操作', 'success': False})
        conn.setex('unanswer_%s_%s' % (pk, user.id), 3600, 'unuseful')
        try:
            reply = Reply.objects.get(pk=pk)
        except Exception as e:
            return JsonResponse({'message': '请勿重复操作', 'success': False})
        reply.unuseful_count += 1
        reply.save()
        return JsonResponse({'message': 'ok', 'success': True})


# 关注标签
class FollowLabel(ModelViewSet):
    queryset = Label.objects.all()
    serializer_class = LabelSerializer
    lookup_field = "id"

    def update(self, request, *args, **kwargs):
        # 1: 获取user对象
        user = request.user
        # 2： 获取recruit对象
        label_id = self.kwargs.get("pk")
        label = Label.objects.get(pk=label_id)

        # 3: 得到所有的user对象
        users = label.users.all()

        if user in users:
            label.users.remove(user)
            return Response(data={"message": "关注成功", "success": True})
        else:
            label.users.add(user)
            return Response(data={"message": "成功取消关注", "success": True})



# # 取关标签
# class UnFollowLabel(View):
#     def put(self, request, pk):
#         user = request.user
#         user.labels.remove(pk)


# 标签详情
class LabelInfo(RetrieveAPIView):
    queryset = Label.objects.all()
    serializer_class = LabelInfoSerializer

    def get_queryset(self):
        label_id = self.kwargs.get('pk')
        return self.queryset.filter(pk=label_id)
